import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/alert_business/video/share_video_dialog.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/acg/comic_chapters_model.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/cartoon_business/widget/acg_source_manager.dart';
import 'package:tiktokadult/hj_page/comment/comment_alert.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/screen.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/widget/follow_button.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';
import 'package:tiktokadult/tools_base/widget/scroll_positioned_list/src/scrollable_positioned_list.dart';

import 'cartoon_read_logic.dart';

//漫画阅读页面
class CartoonReadPage extends StatefulWidget {
  final ACGSourceManager manger;
  const CartoonReadPage({super.key, required this.manger});

  @override
  State<CartoonReadPage> createState() => _CartoonReadPageState();
}

class _CartoonReadPageState extends State<CartoonReadPage> {
  late CartoonReadLogic logic;

  @override
  void initState() {
    logic = Get.put(CartoonReadLogic(widget.manger));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ChangeNotifierProvider<ACGSourceManager>.value(
        value: widget.manger,
        child: GetBuilder<CartoonReadLogic>(
          builder: (_) {
            if (_.detailInfo == null) return LoadingCenterWidget();
            if (_.detailInfo?.id == null) return CErrorWidget(retryOnTap: () => _.loadData());
            return _buildContent();
          },
        ),
      ),
      drawer: _buildDrawer(),
    );
  }

  _buildContent() {
    return Stack(
      alignment: Alignment.center,
      children: [
        InkWell(
          onTap: () => logic.changeShowMenu(),
          child: ScrollablePositionedList.builder(
            scrollAction: (sctr) => logic.onScrollAction(sctr),
            scrollOffsetController: logic.scrollOffsetCtl,
            itemPositionsListener: logic.itemListener,
            itemScrollController: logic.itemSctr,
            itemCount: logic.imgsLength,
            itemBuilder: (context, index) {
              String? mediaUrl = logic.detailInfo?.urlSet?[index];
              return NetworkImageLoader(
                imageUrl: mediaUrl ?? '',
                fit: BoxFit.cover,
                borderRadius: 0,
              );
            },
          ),
        ),
        _buildHeader(),
        _buildFooter(),
        _buildLiked(),
        _buildAutoPlay(),
      ],
    );
  }

  //header bar
  _buildHeader() {
    return GetBuilder<CartoonReadLogic>(
      id: 'header',
      builder: (controller) => AnimatedPositioned(
        duration: Duration(milliseconds: logic.animationTime),
        top: logic.showMenu ? 0 : -90,
        left: 0,
        right: 0,
        child: Container(
          color: Colors.black,
          height: 90,
          padding: EdgeInsets.fromLTRB(10, screen.paddingTop + 10, 10, 10),
          child: Row(
            children: [
              InkWell(
                child: Icon(
                  Icons.arrow_back_ios_new,
                  size: 24,
                  color: Colors.white,
                ),
                onTap: () => Get.back(),
              ),
              10.sizeBoxW,
              Expanded(
                child: Text(
                  logic.detailInfo?.name ?? '',
                  style: TextStyle(fontSize: 18.sp, color: Colors.white, fontWeight: FontWeight.w600),
                ),
              ),
              21.sizeBoxW,
              Consumer<ACGSourceManager>(
                builder: (context, mananger, child) {
                  bool col = mananger.mediaInfo?.mediaStatus?.hasCollected ?? false;
                  return FollowButton(
                    mediaId: mananger.mediaInfo?.id ?? '',
                    isFollow: col,
                    followType: FollowEnum.cartoon,
                    successsAction: (isSuccess) {
                      mananger.updateLikeState(isSuccess);
                      if (isSuccess) {
                        showToast('收藏成功');
                      }
                    },
                  );
                },
              ),
              12.sizeBoxW,
              InkWell(
                onTap: () {
                  Get.dialog(
                    ShareVideoDialog(
                      videoModel: VideoModel()
                        ..id = logic.manager.mediaInfo?.id
                        ..cover = logic.manager.mediaInfo?.coverH,
                    ),
                  );
                },
                child: Image.asset("acg_share.png".acgImgPath, width: 24),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _buildFooter() {
    return GetBuilder<CartoonReadLogic>(
      id: 'footer',
      builder: (controller) => AnimatedPositioned(
        duration: Duration(milliseconds: logic.animationTime),
        bottom: logic.showMenu ? 0 : -logic.bottomHeight,
        left: 0,
        right: 0,
        child: Column(
          children: [
            15.sizeBoxH,
            Obx(
              () => logic.showProgress.value ? _buildProgressView() : 69.sizeBoxH,
            ),
            Container(
                color: Colors.black,
                padding: EdgeInsets.fromLTRB(16, 18, 16, 25),
                child: GetBuilder<CartoonReadLogic>(
                  id: 'actions',
                  builder: (_) {
                    return Row(
                      children: [
                        Expanded(
                          child: Builder(
                            builder: (__) => _buildActionItem(
                                title: '目录',
                                icon: 'cartoon_menu.png'.acgImgPath,
                                action: () async {
                                  Scaffold.of(__).openDrawer();
                                }),
                          ),
                        ),
                        Expanded(
                          child: _buildActionItem(
                              title: '评论',
                              icon: 'cartoon_comment.png'.acgImgPath,
                              action: () async {
                                showCommentDialog(
                                  _.manager.mediaInfo?.id ?? '',
                                  objType: _.manager.mediaInfo?.commentType ?? '',
                                );
                              }),
                        ),
                        Expanded(
                          child: _buildActionItem(
                            title: '进度',
                            icon: 'cartoon_progress.png'.acgImgPath,
                            action: () {
                              logic.showProgress.value = !logic.showProgress.value;
                            },
                          ),
                        ),
                        Expanded(
                          child: _buildActionItem(
                            title: '自动',
                            icon: 'cartoon_auto_play.png'.acgImgPath,
                            action: () {
                              logic.onChangeAutoPlay(true);
                            },
                          ),
                        ),
                      ],
                    );
                  },
                )),
          ],
        ),
      ),
    );
  }

  _buildActionItem({String? title, String? icon, Function()? action, Color? color}) {
    return InkWell(
      child: Column(
        children: [
          Image.asset(icon ?? '', width: 24),
          4.sizeBoxH,
          Text(
            title ?? '',
            style: TextStyle(
              color: color ?? Colors.white.withOpacity(.45),
              fontSize: 12,
              fontWeight: FontWeight.w400,
            ),
          )
        ],
      ),
      onTap: () => action?.call(),
    );
  }

  //自动播放速度
  _buildProgressView() {
    return Container(
      color: Colors.black,
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        children: [
          InkWell(
            onTap: () => logic.loadOtherEpisode(false),
            child: Column(
              children: [
                Image.asset(
                  'common_back_new.png'.commonImgPath,
                  width: 24,
                ),
                4.sizeBoxH,
                Text(
                  '上一篇',
                  style: textStyle(12, Colors.white, FontWeight.w400),
                ),
              ],
            ),
          ),
          13.sizeBoxW,
          Expanded(
            child: Container(
              child: SliderTheme(
                data: SliderTheme.of(context).copyWith(
                  trackHeight: 4, //调整进度条轨道的高度
                  thumbShape: RoundSliderThumbShape(enabledThumbRadius: 8.0), // 调整滑块的大小
                  overlayShape: RoundSliderOverlayShape(overlayRadius: 12.0), // 调整滑块覆盖层的大小
                  tickMarkShape: RoundSliderTickMarkShape(tickMarkRadius: 10.0), // 调整刻度标记的大小
                  trackShape: RoundedRectSliderTrackShape(),
                  overlayColor: Colors.white.withOpacity(.3), // 设置滑块覆盖层的颜色和透明度
                  activeTrackColor: Color(0xffFFD460), // 设置活动进度条的颜色
                  inactiveTrackColor: Colors.white.withOpacity(.3), // 设置非活动进度条的颜色
                  thumbColor: Color(0xffFFD460), // 设置滑块的颜色
                  inactiveTickMarkColor: Colors.amber,
                ),
                child: GetBuilder<CartoonReadLogic>(
                    id: 'slider',
                    builder: (controller) {
                      return Slider(
                        min: 0,
                        max: 1,
                        value: logic.readScale,
                        onChanged: (speed) => logic.updateReadPicIndex(speed),
                      );
                    }),
              ),
            ),
          ),
          13.sizeBoxW,
          InkWell(
            onTap: () => logic.loadOtherEpisode(true),
            child: Column(
              children: [
                Transform.rotate(
                  angle: pi,
                  child: Image.asset(
                    'common_back_new.png'.commonImgPath,
                    width: 24,
                  ),
                ),
                4.sizeBoxH,
                Text(
                  '下一篇',
                  style: textStyle(12, Colors.white, FontWeight.w400),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _buildLiked() {
    return GetBuilder<CartoonReadLogic>(
      id: 'like',
      builder: (controller) => AnimatedPositioned(
        duration: Duration(milliseconds: logic.animationTime),
        bottom: 160,
        right: logic.showMenu ? 0 : -120,
        child: Consumer<ACGSourceManager>(
          builder: (context, manager, child) {
            bool liked = manager.mediaInfo?.mediaStatus?.hasLiked == true;
            return InkWell(
              onTap: () => manager.onLikeAction(),
              child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(.5),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(999),
                      bottomLeft: Radius.circular(999),
                    ),
                  ),
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        liked ? 'acg_like_sel.png'.acgImgPath : 'acg_like_nor.png'.acgImgPath,
                        width: 24,
                        color: liked ? null : Colors.white,
                      ),
                      5.sizeBoxW,
                      Text(
                        '喜欢',
                        style: textStyle(12, Colors.white, FontWeight.w400),
                      ),
                    ],
                  )),
            );
          },
        ),
      ),
    );
  }

  //自动播放组建
  _buildAutoPlay() {
    return Positioned(
      bottom: 30,
      child: GetBuilder<CartoonReadLogic>(
        id: 'autoplay',
        builder: (_) => _.autoPlay
            ? GestureDetector(
                onTap: () => logic.onChangeAutoPlay(false),
                child: Container(
                  height: 56,
                  width: 56,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(28),
                    color: Colors.white,
                  ),
                  child: Center(
                      child: Image.asset(
                    'cartoon_auto_play.gif'.acgImgPath,
                    width: 24,
                  )),
                ),
              )
            : Container(),
      ),
    );
  }

  _buildDrawer() {
    return Obx(() => Container(
          color: Color(0xff030F18),
          width: 210,
          height: screen.screenHeight,
          child: Column(
            children: [
              80.sizeBoxH,
              Row(
                children: [
                  16.sizeBoxW,
                  Expanded(
                    child: Text(
                      logic.manager.mediaInfo?.title ?? '',
                      style: TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                        fontWeight: FontWeight.w900,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
                ],
              ),
              18.sizeBoxH,
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                color: Color(0xffE1351F),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '共${logic.manager.mediaInfo?.totalEpisode}话 ${logic.manager.mediaInfo?.getUpdateString ?? ''}',
                      style: TextStyle(fontSize: 14, color: Colors.white, fontWeight: FontWeight.w400),
                    ),
                    InkWell(
                      onTap: () {
                        logic.sortType.value = !logic.sortType.value;
                        logic.update(['menu']);
                      },
                      child: Row(
                        children: [
                          Image.asset('text_play_sort.png'.acgImgPath, width: 16, height: 16),
                          4.sizeBoxW,
                          Text(
                            logic.sortType.value ? '正序' : '倒序',
                            style: TextStyle(fontSize: 14, color: Colors.white, fontWeight: FontWeight.w400),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                child: ListView.builder(
                  itemCount: logic.manager.allEpisodes.length,
                  padding: const EdgeInsets.only(top: 6, bottom: 20),
                  itemBuilder: (context, index) {
                    //不实用list的reserve，items不够，会从底部开始排，所以采用数据倒序的方法
                    ComicChapterInfo? info;
                    if (logic.sortType.value) {
                      info = logic.manager.allEpisodes[index];
                    } else {
                      info = logic.manager.allEpisodes[logic.manager.allEpisodes.length - index - 1];
                    }
                    return GestureDetector(
                      onTap: () {
                        Get.back();
                        int index = info?.episodeNumber ?? 0;
                        if (index == logic.detailInfo?.episodeNumber) return;

                        if (index > 0) {
                          logic.loadDataWithIndex(index);
                        } else {
                          showToast('数据错误，请联系客服');
                        }
                      },
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        height: 40,
                        child: Row(
                          children: [
                            _buildDrawerItem(
                              '${info.episodeNumber ?? 1}. ${info.name} ',
                              logic.detailInfo?.id == info.id,
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              )
            ],
          ),
        ));
  }

  _buildDrawerItem(String title, bool select) {
    return Expanded(
        child: Text(
      title,
      style: TextStyle(
        fontSize: 16.sp,
        color: select ? AppColors.primaryTextColor : Colors.white,
        fontWeight: select ? FontWeight.w500 : FontWeight.w400,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    ));
  }
}
